package com.streaminggbs.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.streaminggbs.common.base.BaseQueryBean;
import com.streaminggbs.entity.NodeMenuAuth;
import com.streaminggbs.entity.SysAuthMenu;
import com.streaminggbs.entity.SysAuthUserGroup;
import com.streaminggbs.entity.SysAuthUserGroupMenu;
import com.streaminggbs.interfaces.SysAuthMenuService;
import com.streaminggbs.interfaces.SysAuthUserGroupMenuService;
import com.streaminggbs.interfaces.SysAuthUserGroupService;
import com.streaminggbs.mapper.read.SysAuthUserGroupMapperR;
import com.streaminggbs.mapper.write.SysAuthUserGroupMapperW;
import com.streaminggbs.mapper.write.SysAuthUserGroupMenuMapperW;
import com.streaminggbs.common.utils.IDManager;
import com.streaminggbs.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SysAuthUserGroupServiceImpl implements SysAuthUserGroupService {

	@Autowired(required = false)
	private SysAuthUserGroupMapperR sysAuthUserGroupMapperR;
	@Autowired(required = false)
	private SysAuthUserGroupMapperW sysAuthUserGroupMapperW;
    @Autowired
    private SysAuthMenuService sysAuthMenuService;
    @Autowired
    private SysAuthUserGroupMenuService sysAuthUserGroupMenuService;
    @Autowired(required = false)
    private SysAuthUserGroupMenuMapperW sysAuthUserGroupMenuMapperW;

	/**
	 * 保存单个对象
	 * 插入一条数据
	 * 支持Oracle序列,UUID,类似Mysql的INDENTITY自动增长(自动回写)
	 * 优先使用传入的参数值,参数值空时,才会使用序列、UUID,自动增长
	 * @param entity
	 * @return
	 */
	@Override
	public int save(SysAuthUserGroup entity) {
		// TODO Auto-generated method stub
		return sysAuthUserGroupMapperW.insertSelective(entity);
	}

	/**
	 * 根据key删除记录，彻底删除
	 * @param key
	 * @return
	 */
	@Override
	public int delete(Object key) {
		// TODO Auto-generated method stub
		return sysAuthUserGroupMapperW.deleteByPrimaryKey(key);
	}

	/**
	 * 更新所有字段
	 * @param entity
	 * @return
	 */
	@Override
	public int updateAll(SysAuthUserGroup entity) {
		// TODO Auto-generated method stub
		return sysAuthUserGroupMapperW.updateByPrimaryKey(entity);
	}

	/**
	 * 根据主键进行更新
     * 只会更新不是null的数据
	 * @param entity
	 * @return
	 */
	@Override
	public int updateNotNull(SysAuthUserGroup entity) {
		// TODO Auto-generated method stub
		return sysAuthUserGroupMapperW.updateByPrimaryKeySelective(entity);
	}

	/**
	 * 根据主键进行查询,必须保证结果唯一
	 * 单个字段做主键时,可以直接写主键的值
	 * 联合主键时,key可以是实体类,也可以是Map
	 * @param key
	 * @return
	 */
	@Override
	public SysAuthUserGroup selectByKey(Object key) {
		// TODO Auto-generated method stub
		return sysAuthUserGroupMapperR.selectByPrimaryKey(key);
	}

	/**
	 * 根据实体参数获取列表不分页
	 * @param example
	 * @return
	 */
	@Override
	public List<SysAuthUserGroup> selectByExample(Object example) {
		// TODO Auto-generated method stub
		return sysAuthUserGroupMapperR.selectByExample(example);
	}

	/**
	 * 无参数获取列表不分页
	 * @return
	 */
	@Override
	public List<SysAuthUserGroup> selectAll() {
		// TODO Auto-generated method stub
		return sysAuthUserGroupMapperR.selectAll();
	}

	@Override
	public SysAuthUserGroup selectByOther(SysAuthUserGroup entity) {
		// TODO Auto-generated method stub
		return sysAuthUserGroupMapperR.selectOne(entity);
	}
	
	/**
	 * 根据条件分页获取列表
	 * @param baseQueryBean
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	@Override
	public PageInfo<SysAuthUserGroup> selectPageList(BaseQueryBean baseQueryBean,int pageIndex,int pageSize){
		PageHelper.startPage(pageIndex, pageSize, true);
		return new PageInfo<>(sysAuthUserGroupMapperR.selectPageList(baseQueryBean));
	}

    @Override
    public Map<String, Object> preAuthMenu(String usergroupid) {
        Map<String, Object> resultMap = new HashMap<>();
        //查询所有显示的菜单、按钮
        Example exampleMenu = new Example(SysAuthMenu.class);
        Example.Criteria criteriaMenu = exampleMenu.createCriteria();
        criteriaMenu.andEqualTo("displaytype", 1);
        exampleMenu.orderBy("menulevel").asc().orderBy("menusort").asc();
        List<SysAuthMenu> menuList = sysAuthMenuService.selectByExample(exampleMenu);

        List<NodeMenuAuth> nodeMenuList = new ArrayList<>();
        toTree(nodeMenuList, menuList);
        resultMap.put("menuTree", nodeMenuList);

        //查询全选的菜单ID
        Example exampleGroupMenu = new Example(SysAuthUserGroupMenu.class);
        Example.Criteria criteriaGroupMenu = exampleGroupMenu.createCriteria();
        criteriaGroupMenu.andEqualTo("usergroupid", usergroupid);
        criteriaGroupMenu.andEqualTo("isHalf", 0);
        List<SysAuthUserGroupMenu> selectAllMenuList = sysAuthUserGroupMenuService.selectByExample(exampleGroupMenu);
        List<String> expandedKeys = new ArrayList<>();
        if(selectAllMenuList != null && !selectAllMenuList.isEmpty()){
            for(SysAuthUserGroupMenu selectAllMenu: selectAllMenuList){
                expandedKeys.add(selectAllMenu.getMenuid());
            }
        }
        resultMap.put("expandedKeys", expandedKeys);
        return resultMap;
    }

    @Override
    @Transient
    public int setAuthMenu(String usergroupid, String selectAllMenuids, String halfMenuids) {
        //首先删除之前的权限
        Example example = new Example(SysAuthUserGroupMenu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("usergroupid", usergroupid);
        sysAuthUserGroupMenuMapperW.deleteByExample(example);

        //保存全选菜单
        if(!StringUtil.isEmpty(selectAllMenuids)){
            String[] menuidArr = selectAllMenuids.split(",");
            for (String menuid : menuidArr){
                SysAuthUserGroupMenu groupMenu = new SysAuthUserGroupMenu();
                groupMenu.setId(IDManager.nextId());
                groupMenu.setUsergroupid(usergroupid);
                groupMenu.setMenuid(menuid);
                groupMenu.setIsHalf(0);
                sysAuthUserGroupMenuService.save(groupMenu);
            }
        }

        //保存半选菜单
        if(!StringUtil.isEmpty(halfMenuids)){
            String[] menuidArr = halfMenuids.split(",");
            for (String menuid : menuidArr){
                SysAuthUserGroupMenu groupMenu = new SysAuthUserGroupMenu();
                groupMenu.setId(IDManager.nextId());
                groupMenu.setUsergroupid(usergroupid);
                groupMenu.setMenuid(menuid);
                groupMenu.setIsHalf(1);
                sysAuthUserGroupMenuService.save(groupMenu);
            }
        }
        return 1;
    }

    /**
     * 菜单递归
     * @param nodeMenuList
     * @param menuList
     */
    private void toTree(List<NodeMenuAuth> nodeMenuList, List<SysAuthMenu> menuList){
        List<SysAuthMenu> tempMenuList = new ArrayList<>();
        if(nodeMenuList.isEmpty()){
            for(SysAuthMenu menu : menuList){
                if(menu.getMenulevel() == 1){
                    NodeMenuAuth node = new NodeMenuAuth();
                    node.setId(menu.getMenuid());
                    node.setLabel(menu.getMenuname());

                    nodeMenuList.add(node);
                }else{
                    tempMenuList.add(menu);
                }
            }
            toTree(nodeMenuList, menuList);
        }else{
            for(NodeMenuAuth nodeMenu : nodeMenuList){
                for(SysAuthMenu menu : menuList){
                    if(nodeMenu.getId().equals(menu.getParentmenuid())){
                        NodeMenuAuth node = new NodeMenuAuth();
                        node.setId(menu.getMenuid());
                        node.setLabel(menu.getMenuname());

                        nodeMenu.getChildren().add(node);
                    }else{
                        tempMenuList.add(menu);
                    }
                }

                if(!nodeMenu.getChildren().isEmpty() && !tempMenuList.isEmpty()){
                    toTree(nodeMenu.getChildren(), menuList);
                }
            }
        }
    }
}